package com.sgb.capital.view.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.ActivityCheckoutCounterBinding;
import com.sgb.capital.model.BusinessInfoByCompanyEntity;
import com.sgb.capital.model.PayCardEntity;
import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.router.PathCapital;
import com.sgb.capital.utils.CryptoUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.NewPayPop;
import com.sgb.capital.view.pop.PaySelectPop;
import com.sgb.capital.view.pop.PayTipPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.adapter.PayCardAdapter;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.CheckoutCounterModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/10/26 0015
 * 说明:个人支付办理 企业:PayDealActivity
 */
@Route(path = PathCapital.PersonPayActivity)
public class PersonPayActivity extends BaseActivity implements NewPayPop.OnPopClickListener {
    CheckoutCounterModel mModel;
    ActivityCheckoutCounterBinding mBinding;
    PayTipPop mPayTipPop;
    TipPop mTip;
    Map<String, Object> map = new HashMap<>();
    Map<String, Object> mBalancemap = new HashMap<>();
    private List<PayCardEntity> dataList = new ArrayList<>();
    PayCardAdapter mAdapter;
    private String mPriceTv = "";
    public String mOrderId;
    private PaySelectPop mPaySelectPop;
    private PayInfoEntity mPayInfoEntity;
    private NewPayPop mPayPop;
    private BusinessInfoByCompanyEntity mInfoByCompanyEntity;
    private String mType;
    private long mIndex;
    private String mIsPayBalance; // 是否可以余额支付
    private CountDownTimer mTimer;
    private boolean mIsTimeOut;
    private DecimalFormat mDecimalFormat;
    private boolean isErrorMoney;
    private boolean isError;

    public static void start(Activity context, String data, int code, boolean isUser) {
        Intent intent = new Intent();
        intent.putExtra("data", data);
        intent.putExtra("isUser", isUser);
        intent.setClass(context, PersonPayActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivityForResult(intent, code);
    }

    /**
     * @param context 上下文
     * @param orderId 订单id
     */
    public static void start(Activity context, String orderId) {
        Intent intent = new Intent();
        intent.putExtra("orderId", orderId);
        intent.setClass(context, PersonPayActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_checkout_counter);
        mModel = new ViewModelProvider(this).get(CheckoutCounterModel.class);
        mAdapter = new PayCardAdapter(this, null, position -> AddAndEditCardsActivity.start(PersonPayActivity.this, dataList.get(position).id));
        mBinding.cardList.setLayoutManager(new LinearLayoutManager(this));
        mOrderId = getIntent().getStringExtra("orderId");
        mPaySelectPop = new PaySelectPop(this);
        mBinding.cardList.setAdapter(mAdapter);
        mDecimalFormat = new DecimalFormat("#0.00");
        mPriceTv = "¥" + "0.00";
        mBinding.tvDeal.setVisibility(View.VISIBLE);
        mBinding.price.setText(mPriceTv);
        mBinding.buyButton.setText("银行卡支付 " + mPriceTv);
        mModel.getQuick(this);
        mModel.orderOvertime(this, mOrderId);
        mTip = new TipPop(PersonPayActivity.this, "温馨提示", "银行卡信息错误，请重新核对信息", null, "确定");
        mPayTipPop = new PayTipPop(mContext);
        mPayTipPop.tvCall.setOnClickListener(v -> callPhone());
        mModel.mPayCardList.observe(this, payCardEntities -> setData(payCardEntities));
        mPayPop = new NewPayPop(this, this);
        mPayPop.mTvTitle.setText("付款验证码");
        mPayPop.mPayButton.setText("立即付款");
        mPayPop.mTvOk.setText("付款成功");
        mPayPop.mBackOrder.setText("返回订单");
        mPayPop.mTvTip.setText("付款成功");
        mBinding.llBalancePayBtn.setEnabled(false);
        mBinding.llQuickPayBtn.setEnabled(false);
        mModel.pay2Info(this, mOrderId);
    }

    public void setData(List<PayCardEntity> data) {
        dataList.clear();
        dataList.addAll(data);
        if (dataList.size() > 0) {
            mBinding.cardList.setVisibility(View.VISIBLE);
            mAdapter.setDatas(dataList);
        } else {
            mBinding.cardList.setVisibility(View.GONE);
        }
    }

    //显示验证码输入错误的弹框
    public void showErrorCode(String type, String tip) {
        mType = type;
        if ("E000011".equals(type)) {
            mTip.initStr("复核人员状态已变更，请重新选择！", null, "知道了");
            mTip.show();
        } else if ("E000012".equals(type)) {
            mTip.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
            mTip.show();
        } else if ("E000013".equals(type)) {
            isErrorMoney = true;
            mTip.initStr("您已向当前商户支付过一笔相同金额的订单，请确认是否继续支付！", "继续支付", "放弃");
            mTip.show();
            return;
        } else if ("E000007".equals(type)) {
            mPayTipPop.show();
        } else if ("E000008".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if ("E000009".equals(type)) {
            mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
            mTip.show();
            isError = true;
        } else if ("E0000010".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if ("E00463031".equals(type)) {
            mTip.initStr("银行卡信息错误，请重新核对信息", null, "知道了");
            mTip.show();
        } else if ("E00000003".equals(type)) {
            mTip.initStr("可用余额不足，请充值余额或更换其他支付方式！", null, "知道了");
            mTip.show();
            mPayPop.dismiss();
        } else if ("E00462012".equals(type)) {
            mTip.initStr(tip, null, "知道了");
            mTip.show();
        } else if (type.contains("E00466311")) {
            mIndex++;
            if (mIndex > 3) {
                mTip.initStr("支付失败，请重新支付", null, "知道了");
                mTip.show();
                mPayPop.dismiss();
                return;
            }
            mPayPop.setTipText("验证码错误");
        } else {
            MToast.showToast(Utils.getContext(), tip);
        }
    }

    //重新请求验证码需要传上一次的返回值，merTrace
    public void setApplyCount(String s) {
        mPayPop.mPayLayout.setVisibility(View.VISIBLE);
        mPayPop.mPaySuccessLayout.setVisibility(View.GONE);
        mIndex = 0;
        if (mBinding.llBalancePay.getVisibility() == View.VISIBLE) {
            mPayPop.show();
            mPayPop.setStartTimer();
            return;
        }
        map.put("merTrace", s);
        mPayPop.show();
        mPayPop.setStartTimer();
    }

    //订单支付成功
    public void setConfirm() {
        mPayPop.mPayLayout.setVisibility(View.GONE);
        mPayPop.mPaySuccessLayout.setVisibility(View.VISIBLE);
        Utils.sendMsg(Constants.EVENT_PAY_SUCCESS, null);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH:
                mModel.getQuick(this);
                break;
            case Constants.EVENT_CLICK:
                //  payPop.clearData();
                break;
            case Constants.TIMEOUT:
                mTip.initStr("温馨提示", "支付超时，请重新发起支付", null, "知道了");
                mTip.show();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!TextUtils.isEmpty(mOrderId)) {
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void callPhone() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + "400-001-0051");
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void initListener() {
        mBinding.addNewCard.setOnClickListener(v -> startActivity(new Intent(PersonPayActivity.this, AddAndEditCardsActivity.class)));
        mBinding.tvDeal.setOnClickListener(v -> {
            DealLimitActivity.start(this);
        });
        mPayTipPop.mTvSure.setOnClickListener(v -> {
            Utils.sendMsg(Constants.EVENT_REFRESH_ORDER, null);
            mPayTipPop.dismiss();
            finish();
        });

        mPayPop.mBackOrder.setOnClickListener(v -> {
            Utils.sendMsg(Constants.EVENT_REFRESH_ORDER, null);
            mPayPop.dismiss();
            finish();
        });
        mBinding.ivBack.setOnClickListener(v -> {
            mTip.initStr("您要放弃此次支付吗?", "继续支付", "放弃");
            mTip.show();
        });
        mTip.mTvCancel.setOnClickListener(v -> {
            mTip.dismiss();
            if (mTip.mTip.contains("放弃")) {
                finish();
                return;
            }
            if (Utils.isEmpty(mType)) {
                return;
            }
            if (mType.equals("E00000003")) {
                mModel.pay2Info(this, mPayInfoEntity.orderId);
                return;
            }
            if (mType.contains("E000003")) {
                return;
            }
            if (mTip.mTvCancel.getText().toString().contains("放弃")) {
                if (!isErrorMoney) {
                    finish();
                }
                return;
            }
            if (mIsTimeOut) {
                mModel.pay2Info(this, mPayInfoEntity.orderId);
            }
            if (mType.equals("E0000011") || mType.equals("E0000012")) {
                mModel.getBusinessInfoByUser(this);
                return;
            }
            if (isError) {
                startActivity(new Intent(this, OrderErrorActivity.class));
                return;
            }
        });
        mTip.mTvSure.setOnClickListener(v -> {
            mTip.dismiss();
            if (mTip.mTvSure.getText().toString().contains("继续") && isErrorMoney) {
                String mobileId = mInfoByCompanyEntity.mobileId;
                mPayPop.mPhoneNumber.setText("请输入手机验证码(" + mobileId.substring(0, 3) + "****" + mobileId.substring(mobileId.length() - 4) + ")");
                mPayPop.mClickListener.onClickNewGet();
            }
        });
        mBinding.buyButton.setOnClickListener(v -> {
            if (mPayInfoEntity == null) {
                MToast.showToast(Utils.getContext(), "数据异常");
                return;
            }
            mModel.payValidation(PersonPayActivity.this, mPayInfoEntity.tradeNo, "");
        });

        mPaySelectPop.mTvQuickPayBtn.setOnClickListener(v -> {
            mPaySelectPop.dismiss();
            mBinding.llQuickPay.setVisibility(View.VISIBLE);
            mBinding.llBalancePay.setVisibility(View.GONE);
            mBinding.buyButton.setEnabled(true);
            mBinding.buyButton.setText("银行卡支付 " + mPriceTv);
            mBinding.buyButton.setBackground(Utils.getResources().getDrawable(R.drawable.button2));
        });
        mPaySelectPop.mTvBalancePayBtn.setOnClickListener(v -> {
            mPaySelectPop.dismiss();
            if (!Utils.isEmpty(mIsPayBalance)) {
                mTip.initStr("当前订单余额支付不可用，请更换其\n他支付方式进行支付", null, "确实");
                mTip.show();
                return;
            }
            mBinding.llQuickPay.setVisibility(View.GONE);
            mBinding.llBalancePay.setVisibility(View.VISIBLE);
            mBinding.buyButton.setText("余额支付 " + mPriceTv);
            mBinding.buyButton.setEnabled(mBinding.tvMoneyTip.getVisibility() == View.VISIBLE ? false : true);
            mBinding.buyButton.setBackground(Utils.getResources().getDrawable(mBinding.tvMoneyTip.getVisibility() == View.VISIBLE ? R.drawable.button2_false : R.drawable.button2));

        });
        mBinding.llBalancePayBtn.setOnClickListener(v -> {
            if (mIsTimeOut) {
                mTip.initStr("温馨提示", "支付超时，请重新发起支付", null, "知道了");
                mTip.show();
                return;
            }
            mPaySelectPop.show(mBinding.view);
        });

        mBinding.llQuickPayBtn.setOnClickListener(v -> {
            mPaySelectPop.show(mBinding.view);
        });
    }

    @Override
    public void initObserve() {
        mModel.mState.observe(this, s -> {
            if (Utils.isEmpty(s)) {
                if (mBinding.llBalancePay.getVisibility() == View.VISIBLE) {
                    String mobileId = mInfoByCompanyEntity.mobileId;
                    mPayPop.mPhoneNumber.setText("请输入手机验证码(" + mobileId.substring(0, 3) + "****" + mobileId.substring(mobileId.length() - 4) + ")");
                    mPayPop.mClickListener.onClickNewGet();
                    return;
                }
                if (mAdapter.getSelectPosition() == -1) {
                    MToast.showToast(PersonPayActivity.this, "请选择支付银行卡");
                    return;
                }
                PayCardEntity entity = dataList.get(mAdapter.getSelectPosition());
                String mobileId = CryptoUtils.decryptAES_ECB(entity.phone);
                mPayPop.mPhoneNumber.setText("请输入手机验证码(" + mobileId.substring(0, 3) + "****" + mobileId.substring(mobileId.length() - 4) + ")");
                mPayPop.mClickListener.onClickNewGet();
                return;
            }
            if ("E000001".equals(s)) {
                isError = true;
                mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
                mTip.show();
            } else if ("E000007".equals(s)) {
                mPayTipPop.show();
            } else if ("E000003".equals(s)) {
                isErrorMoney = true;
                mTip.initStr("您已向当前商户支付过一笔相同金额的订单，请确认是否继续支付！", "继续支付", "放弃");
                mTip.show();
            } else if ("E000009".equals(s)) {
                isError = true;
                mTip.initStr("订单异常，无法付款，可前往业务管理-异常订单查看详情！", null, "知道了");
                mTip.show();
            } else if ("E0000012".equals(s)) {
                mTip.initStr("复核人员为空，请在电脑端-业务管理-复核配置进行相关人员的配置！", null, "知道了");
                mTip.show();
                return;
            } else if ("E0000011".equals(s)) {
                mTip.initStr("复核人员状态已变更，请重新选择！", null, "知道了");
                mTip.show();
            } else if ("E0000013".equals(s)) {
                mTip.initStr("支付超时，请重新发起支付", null, "知道了");
                mTip.show();
            } else if ("E00000003".equals(s)) {
                mTip.initStr("可用余额不足，请充值余额或更换其他支付方式！", null, "知道了");
                mTip.show();
                mPayPop.dismiss();
            }
        });

        mModel.mPayInfo.observe(this, payInfoEntity -> {

            mPayInfoEntity = payInfoEntity;
            mPriceTv = "¥" + mDecimalFormat.format(mPayInfoEntity.amount);
            mBinding.price.setText(mPriceTv);
            mBinding.buyButton.setText("银行卡支付 " + mPriceTv);
            mPayPop.mPayPriceTv.setText(mPriceTv);
            mModel.getBusinessInfoByUser(this);
            mIsTimeOut = false;
            mPayPop.mIsTimeOut = false;
            int time = payInfoEntity.orderLimitTime * 1000;
            mTimer = new CountDownTimer(time, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    long day = millisUntilFinished / (1000 * 60 * 60 * 24);/*单位天*/
                    long hour = (millisUntilFinished - day * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);/*单位时 */
                    long minute = (millisUntilFinished - day * (1000 * 60 * 60 * 24) - hour * (1000 * 60 * 60)) / (1000 * 60);/*单位分以*/
                    AtomicLong second = new AtomicLong((millisUntilFinished - day * (1000 * 60 * 60 * 24) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000);/*单位秒*/
                    String key = hour + "小时" + minute + "分" + second + "秒";
                    if (second.get() == 1) {
                        Utils.postDelay(() -> second.set(0), 1000);
                    }
                    mBinding.tvTime.setText(Utils.getKeyWordSpan(Utils.getColor(R.color.color_FF6600), "请在" + key + "内完成支付！", key));
                    mBinding.tvTime.setVisibility(View.VISIBLE);
                }

                @Override
                public void onFinish() {
                    mTimer.cancel();
                    mIsTimeOut = true;
                    mPayPop.mIsTimeOut = true;
                }
            };
            mTimer.start();
        });
        mModel.mCode.observe(this, s -> mIsPayBalance = s);
        mModel.mUserBusinessInfoByCompanyEntity.observe(this, info -> {
            if (info == null || Utils.isEmpty(info.custName) || Utils.isEmpty(info.mobileId)) {
                mBinding.llBalancePayBtn.setEnabled(false);
                mBinding.llQuickPayBtn.setEnabled(false);
                mBinding.ivKj.setVisibility(View.GONE);
                mBinding.ivArrow.setVisibility(View.GONE);
                return;
            }
            mBinding.llQuickPayBtn.setEnabled(true);
            mBinding.llBalancePayBtn.setEnabled(true);
            mBinding.ivArrow.setVisibility(View.VISIBLE);
            mInfoByCompanyEntity = info;
            mBinding.tvNamePhone.setText(info.custName + " (" + info.mobileId.substring(0, 3) + "****" +
                    info.mobileId.substring(info.mobileId.length() - 4) + ")");
            mBinding.tvMoney.setText("￥" + Utils.getDecimalFormat(info.balance));
            if (info.balance - mPayInfoEntity.amount >= 0) {
                mBinding.tvMoneyTip.setVisibility(View.GONE);
            } else {
                mBinding.tvMoneyTip.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onClickNewGet() {
        if (mBinding.llBalancePay.getVisibility() == View.VISIBLE) {
            mBalancemap.put("amount", mPayInfoEntity.amount);
            mBalancemap.put("phone", mInfoByCompanyEntity.mobileId);
            mBalancemap.put("tradeNo", mPayInfoEntity.tradeNo);
            mBalancemap.put("payUserName", mInfoByCompanyEntity.custName);
            mModel.balancePayApply(this, mBalancemap);
        } else {
            map.put("amount", mPayInfoEntity.amount);
            map.put("gateId", dataList.get(mAdapter.getSelectPosition()).gateId);
            map.put("payBandCardId", dataList.get(mAdapter.getSelectPosition()).id);
            map.put("payType", "QP");
            map.put("tradeNo", mPayInfoEntity.tradeNo);
            mModel.quickPayOrderApply(PersonPayActivity.this, map);
        }
    }

    @Override
    public void onClickPayButton(String vCode) {
        if (mBinding.llBalancePay.getVisibility() == View.VISIBLE) {
            mBalancemap.put("code", vCode);
            mModel.balancePayConfirm(this, mBalancemap);
        } else {
            map.put("verifyCode", vCode);
            mModel.quickPayOrderConfirm(PersonPayActivity.this, map);
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        Utils.sendMsg(Constants.EVENT_REFRESH, null);
        if (mTimer != null) {
            mTimer.cancel();
        }
        super.onDestroy();
    }
}